#include <iostream>

#include <mysql.h>

#include "db.h"
#include "db_op.h"
#include "db_info.h"


// 构造函数
Library_Database::Library_Database() : Database() {
    // 初始化连接指针为nullptr
}

// 析构函数
Library_Database::~Library_Database() {
    if (conn != nullptr) {
        mysql_close(conn);  // 关闭数据库连接
    }
}

// 连接数据库
bool Library_Database::connect(DatabaseInfo* db_info) {
    conn = mysql_init(nullptr);
    if (!conn) {
#ifdef DEBUG_PRINTS
        std::cerr << "mysql_init failed" << std::endl;
#endif
        return false;
    }

    if (mysql_real_connect(conn, db_info->host.c_str(), db_info->user.c_str(),
        db_info->passwd.c_str(), db_info->dbname.c_str(),
        db_info->port, nullptr, 0) == nullptr) {
#ifdef DEBUG_PRINTS
        std::cerr << "mysql_real_connect failed: " << mysql_error(conn) << std::endl;
#endif
        mysql_close(conn);
        conn = nullptr;
        return false;
    }

    // 设置字符集
    mysql_set_character_set(conn, "utf8");
    return true;
}

// 处理连接后的操作
void Library_Database::accept(Database_Operater* db_op, const char* op) {
    if (conn != nullptr) {
        db_op->DatebaseOperation(conn,op);
    }
    else {
#ifdef DEBUG_PRINTS
        std::cerr << "No connection to accept. Please connect first." << std::endl;
#endif
    }
}
